package com.woohua.thread.lockscene;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/***
 * @title ReentrantLockCache
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/21 11:15
 **/
public class ReentrantLockCache {

    final Map<Integer, Integer> map = new HashMap<>();
    ReentrantLock readLock = new ReentrantLock();

    public void put(Integer key, Integer val) {
        try {
            readLock.lock(); // 写锁
            ReentrantLockDemo.sleep(1000);  // 短暂休眠，用于验证读写互斥
            map.put(key, val);
        }finally {
            readLock.unlock();  // 必须在finally块解锁
        }
    }

    public Integer get(Integer key) {
        try {
            readLock.lock();    // 读锁
            ReentrantLockDemo.sleep(1000);  // 短暂休眠，用于验证读写互斥
            return map.get(key);
        }finally {
            readLock.unlock();  // 必须在finally块解锁
        }
    }

}
